const { jwtVerify, Resp } = require('../config/utils')
const log = require('../config/log').log
const redis = require('../config/redis')
const tokens = require('../config/clientToken')
module.exports = async (ctx, next) => {
  const { vf } = ctx.headers
  const { type } = ctx.params
  if(!vf) {
    ctx.status = 401
    return ctx.body = Resp(0, '缺少token!', null)
  }

  let authClientToken = false
  Object.keys(tokens).forEach(t => {
    if(vf === tokens[t]) {
      authClientToken = true
    }
  })
  if(authClientToken) {
    log(`${ctx.method} ${ctx.request.originalUrl} ${ctx.request.headers["x-real-ip"] || ctx.request.headers['x-forwarded-for']}[token]${vf}[msg] ${type}使用clientToken认证！\n`, 'clientToken')
    return next()
  }
  let info = null
  try { 
    info = jwtVerify(vf)
    ctx.user = info
  } catch (error) {
    log(
      ` ${ctx.method} ${ctx.request.originalUrl} ${ctx.request.headers["x-real-ip"] || ctx.request.headers['x-forwarded-for']}[token]${vf}[msg] ${'token已过期!'}\n`, 'error')
    switch (error.name) {
      case 'TokenExpiredError':
        ctx.status = 403
        return ctx.body = Resp(0, 'token已过期!', null)
        break;
      default:
        ctx.status = 403
        return ctx.body = Resp(0, 'token校验失败!', null)
        break;
    }
  }
  let result = await redis.hgetAsync('loginInfo', info.data._id)
  if(result === vf){
    await next()
  }else {
    log(` ${ctx.method} ${ctx.request.originalUrl} ${ctx.request.headers["x-real-ip"] || ctx.request.headers['x-forwarded-for']}[token]${vf}[msg] ${'token已过期!'}\n`, 'error')
    ctx.status = 403
    return ctx.body = Resp(0, 'token已过期!', null);
  }
}